package com.zgzg.shop.pay.base.utils;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import org.dom4j.Attribute;
import org.dom4j.DocumentException;
import org.dom4j.DocumentHelper;
import org.dom4j.io.SAXReader;
import org.springframework.util.StringUtils;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

import javax.servlet.http.HttpServletRequest;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class XmlUtil {
    /**
     *
     * @param strXML 解密过后的xml字符串
     * @return 该字符串对应的map
     * @throws Exception
     */
    public static Map<String, String> xmlToMap(String strXML) throws Exception {
        try {
            Map<String, String> data = new HashMap<>();
            DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
            DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder();
            InputStream stream = new ByteArrayInputStream(strXML.getBytes(StandardCharsets.UTF_8));
            Document doc = documentBuilder.parse(stream);
            doc.getDocumentElement().normalize();
            NodeList nodeList = doc.getDocumentElement().getChildNodes();
            for (int idx = 0; idx < nodeList.getLength(); ++idx) {
                Node node = nodeList.item(idx);
                if (node.getNodeType() == Node.ELEMENT_NODE) {
                    Element element = (Element) node;
                    data.put(element.getNodeName(), element.getTextContent());
                }
            }
            try {
                stream.close();
            } catch (Exception ex) {
            }
            return data;
        } catch (Exception ex) {
            throw ex;
        }

    }

    /**
     *
     * @param param 封装好的map对象
     * @return 对应的xml字符串形式
     */
    public static String mapToXml(Map<String, Object> param) {

        StringBuffer strbuff = new StringBuffer("<xml>");

        if (param != null && !param.isEmpty()) {
            for (Map.Entry<String, Object> entry : param.entrySet()) {
                strbuff.append("<").append(entry.getKey()).append(">");
                strbuff.append("<![CDATA[");
                if (!StringUtils.isEmpty(entry.getValue())) {
                    strbuff.append(entry.getValue());
                }
                strbuff.append("]]>");
                strbuff.append("</").append(entry.getKey()).append(">");
            }
        }
        return strbuff.append("</xml>").toString();
    }

    /**
     * @Description: 请求转json
     * @Author: qy
     * @return: com.alibaba.fastjson.JSONObject
     **/
    public static JSONObject xmlToJson(HttpServletRequest request) throws IOException {
        //dom4j saxReader解析xml
        SAXReader reader=new SAXReader();
        //从request中获取输入流
        InputStream ins = request.getInputStream();
        //解析xml文档
        org.dom4j.Document doc = null;
        try {
            doc = reader.read(ins);
        } catch (org.dom4j.DocumentException e) {
            e.printStackTrace();
        }
        return xmlToJson(doc);
    }


    public static JSONObject xmlToJson(org.dom4j.Document doc) {
        JSONObject json = new JSONObject();
        dom4j2Json(doc.getRootElement(), json);
        return json;
    }


    public static JSONObject xmlToJson(String xmlStr) throws DocumentException {
        org.dom4j.Document doc = DocumentHelper.parseText(xmlStr);
        JSONObject json = new JSONObject();
        dom4j2Json(doc.getRootElement(), json);
        return json;
    }

    /**
     * xml转json
     * @param element
     * @param json
     */
    public static void dom4j2Json(org.dom4j.Element element, JSONObject json) {
        //如果是属性
        for (Object o : element.attributes()) {
            Attribute attr = (Attribute) o;
            if (!StringUtils.isEmpty(attr.getValue())) {
                json.put("@" + attr.getName(), attr.getValue());
            }
        }
        List<org.dom4j.Element> chdEl = element.elements();
        if (chdEl.isEmpty() && !StringUtils.isEmpty(element.getText())) {//如果没有子元素,只有一个值
            json.put(element.getName(), element.getText());
        }

        for (org.dom4j.Element e : chdEl) {//有子元素
            if (!e.elements().isEmpty()) {//子元素也有子元素
                JSONObject chdjson = new JSONObject();
                dom4j2Json(e, chdjson);
                Object o = json.get(e.getName());
                if (o != null) {
                    JSONArray jsona = null;
                    if (o instanceof JSONObject) {//如果此元素已存在,则转为jsonArray
                        JSONObject jsono = (JSONObject) o;
                        json.remove(e.getName());
                        jsona = new JSONArray();
                        jsona.add(jsono);
                        jsona.add(chdjson);
                    }
                    if (o instanceof JSONArray) {
                        jsona = (JSONArray) o;
                        jsona.add(chdjson);
                    }
                    json.put(e.getName(), jsona);
                } else {
                    if (!chdjson.isEmpty()) {
                        json.put(e.getName(), chdjson);
                    }
                }
            } else {//子元素没有子元素
                for (Object o : element.attributes()) {
                    Attribute attr = (Attribute) o;
                    if (!StringUtils.isEmpty(attr.getValue())) {
                        json.put("@" + attr.getName(), attr.getValue());
                    }
                }
                if (!e.getText().isEmpty()) {
                    json.put(e.getName(), e.getText());
                }
            }
        }
    }

    /*public static void main(String[] args) {
        TouTiaoArticleRSSDTO.Item item = new TouTiaoArticleRSSDTO.Item();
        item.setTitle("item title");
        item.setLink("https://csi.tmuyun.com/");
        item.setDescription("<p>item description</p>");
        item.setPubDate(DateFormatUtils.format(new Date(), DateTimeUtils.DATE_TIME_PATTERN));

        List<TouTiaoArticleRSSDTO.Item> items = new ArrayList<>();
        items.add(item);

        TouTiaoArticleRSSDTO.Channel channel = new TouTiaoArticleRSSDTO.Channel();
        channel.setTitle("");
        channel.setDescription("");
        channel.setLanguage("zh-cn");
        channel.setLink("https://csi.tmuyun.com/");
        channel.setItemList(items);

        TouTiaoArticleRSSDTO touTiaoArticleRSSDTO = new TouTiaoArticleRSSDTO();
        touTiaoArticleRSSDTO.setChannel(channel);

        String beanToXml = beanToXml(touTiaoArticleRSSDTO);
        System.out.println(beanToXml);
        String fileName = generatorXmlFile(PATH, beanToXml);
        System.out.println(fileName);

        new File(PATH + File.separator + fileName).delete();
        new File(PATH).delete();
        new File(System.getProperty("user.dir") + File.separator + "temp").delete();
    }*/

}
